package com.example.springsecurity.service;

import com.example.springsecurity.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MyUserDetailService implements UserDetailsService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    //模拟sql数据库
    public static ConcurrentHashMap<String,UserDetails> userDetailMap = new ConcurrentHashMap<>();


    @PostConstruct
    public void init(){
        GrantedAuthority[] authorities = new GrantedAuthority[2];
        authorities[0]= ()->"Student:add";
        authorities[1]= ()->"Student:delete";

        UserDetails zs = new LoginUser("zs", passwordEncoder.encode("123456"), Arrays.asList(authorities));
        UserDetails ls = new LoginUser("ls", passwordEncoder.encode("123456"), Arrays.asList(authorities));

        userDetailMap.put("zs",zs);
        userDetailMap.put("ls",ls);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails = userDetailMap.get(username);
        if (userDetails==null){
            throw new UsernameNotFoundException(username);
        }
        return userDetails;
    }
}
